package com.cat.model.biz.service.api.impl;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alonew.json.JSONArray;
import com.alonew.json.JSONException;
import com.alonew.json.JSONObject;
import com.cat.model.biz.service.api.UserFavoriteService;
import com.cat.model.biz.service.bs.UserFavoriteBS;
import com.cat.model.common.enumerator.TargetType;
import com.cat.model.common.model.common.ModelInfoVO;
import com.cat.model.common.model.common.UserFavoriteVO;
import com.cat.model.common.util.ErrorCode;
import com.cat.model.common.util.ImageUtil;
import com.cat.model.common.util.PageUtil;
import com.cat.model.dao.mapper.ModelMapper;
import com.cat.model.web.bean.UserFavListBean;


@Service("userFavoriteService")
public class UserFavoriteServiceImpl implements UserFavoriteService{
	@Autowired
	private UserFavoriteBS userFavoriteBS;
	
	@Autowired
	private ModelMapper modelMapper;
	
	@Override
	public String addUserModelFavorite(Long userId, Long ModelId) {
		
		userFavoriteBS.addUserFavorite(userId, ModelId, TargetType.Model);
		
		return ErrorCode.OK.response();
	}

	@Override
	public String delUserModelFavorite(Long userId, Long ModelId) {
		userFavoriteBS.delUserFavorite(userId, ModelId, TargetType.Model);
		
		return ErrorCode.OK.response();
	}

	@Override
	public String getUserModelFavoriteList(Long userId, int page, int size) {
		List<UserFavoriteVO> favList = userFavoriteBS.getUserFavoriteList(userId, TargetType.Model);
		
		JSONObject json = ErrorCode.OK.responseJSON();
		List<UserFavListBean> beanList = new ArrayList<UserFavListBean>();
		if(favList == null || favList.size() <= 0){
			try {
				json.put("data", new JSONArray(beanList));
			} catch (JSONException e) {
				return ErrorCode.SERVER_ERROR.response();
			}
			return json.toString();
		}
		
		for(UserFavoriteVO vo : favList){
			ModelInfoVO model = modelMapper.getModelInfo(vo.getTargetId());
			if(null == model){
				continue;
			}
			
			UserFavListBean bean = new UserFavListBean();
			
			bean.setModelId(model.getId());
			bean.setCoverImage(ImageUtil.wrapImageUrl(model.getCoverImage()));
			bean.setName(model.getName());
			bean.setAge(model.getAge());
			bean.setSex(model.getSex());
			bean.setCityCode(model.getCityCode());
			bean.setCountryCode(model.getCountryCode());
			bean.setPrice(model.getPrice());
			bean.setModelCode(model.getModelCode());
			
			beanList.add(bean);
		}
		
		 int[] indexs = PageUtil.getStartAndEnd(page, size, beanList.size());
		 List<UserFavListBean> resultList = beanList.subList(indexs[0], indexs[1]);
		
		try {
			json.put("data", new JSONArray(resultList));
		} catch (JSONException e) {
			return ErrorCode.SERVER_ERROR.response();
		}
		
		return json.toString();
	}
	
}
